import {
    defineStore
} from 'pinia'
import {
    ref,
    reactive
} from 'vue'
import {
    getUsermsg
} from '../api/login/index.js'

export const useAuthStore = defineStore('auth', () => {
    const token = ref('')
    const user = reactive({
        id: '',
        username: '',
        phone: '',
        email: '',
        created: '',
        updated: ''
    })

    const login = async (credentials) => {
        const res = await getUsermsg(credentials)
        token.value = res.token
        Object.assign(user, res.user)
        localStorage.setItem('token', res.token)
        localStorage.setItem('user', JSON.stringify(res.user))
        return res
    }

    const logout = () => {
        token.value = ''
        Object.keys(user).forEach(key => user[key] = '')
        localStorage.removeItem('token')
        localStorage.removeItem('user')
    }

    return {
        token,
        user,
        login,
        logout
    }
})